from django.shortcuts import render, redirect
from .models import *
# Create your views here.
def show_index(request):

    depts = DeptInfo.objects.all()
    return render(request, 'dept/commodity-dept.html', {'depts': depts})
    #return render(request, 'dept/commodity-dept.html')


def show_add_index(request):
    return render(request, 'dept/deptAdd.html')


def add_dept(request):
    if request.POST:
        # 获取请求参数
        deptname = request.POST.get('deptname', '')
        deptID = request.POST.get('ID', '')
        deptdescription =request.POST.get('deptdescription','')
        # print(brandname)
        # print(brandID)
        # 查询数据库
        if deptname and deptID and deptdescription :
            brandcount = DeptInfo.objects.filter(name=deptname, id=deptID,description=deptdescription).count()
            if brandcount == 0:
                # print(brandcount)
                # 创建模型对象
                dept = DeptInfo(name=deptname, id=deptID,description=deptdescription)
                # 插入数据库
                dept.save()
                return redirect('/dept/show')
        return redirect('/dept/add')
def show_update_index(request,id):
    dept = DeptInfo.objects.get(id=id)
    return render(request, 'dept/deptUpdate.html',{'dept': dept})


def update_dept(request):
    if request.POST:
        oldname = request.POST.get('oldname')
        oldid = request.POST.get('oldid')
        olddescription = request.POST.get('olddescription')
        dept = DeptInfo.objects.get(id=oldid)
        # 获取请求参数
        deptname = request.POST.get('deptname', '')
        deptID = request.POST.get('ID', '')
        deptdescription =request.POST.get('deptdescription', '')
        dept.id = deptID
        dept.name = deptname
        dept.description =deptdescription
        print(deptname)
        print(deptID)
        dept.save()
        return redirect('/dept/show/')

def delete_dept(request,id):
    print(id)
    dept = DeptInfo.objects.get(id=id)
    dept.delete()
    return redirect('/dept/show/')

